package com.satis.compose.get

import androidx.compose.runtime.*
import androidx.compose.ui.graphics.Color
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch
import java.lang.reflect.ParameterizedType

/**
 * @author sunshaobei on 2022/9/9
 */
abstract class GetViewModel<_Intent, _UIState> : ViewModel() {
    private val channel = Channel<_Intent>(Channel.UNLIMITED)
    var uiState:_UIState by mutableStateOf(invokeUiState())

    @Suppress("UNCHECKED_CAST")
    private fun invokeUiState(): _UIState {
        val type = this.javaClass.genericSuperclass as ParameterizedType
        val actualTypeArguments = type.actualTypeArguments
        //init default UIState
        val state = actualTypeArguments[1] as Class<_UIState>
        return state.newInstance() as _UIState
    }

    fun sentIntent(intent: _Intent){
        viewModelScope.launch {
            channel.send(intent)
        }
    }


    fun setState(state:_UIState){
        this.uiState = state
    }

    init {
        viewModelScope.launch {
            channel.consumeAsFlow().collect {
                dispatch(it)
            }
        }
    }
    abstract suspend fun dispatch(it: _Intent)
}